<template>
  <div class="app-container">
    <div class="filter-container">
      <el-card class="filter-card">
        <el-form :inline="true" :model="listQuery" class="form-inline">
          <el-form-item label="订单状态">
            <el-select v-model="listQuery.status" placeholder="全部状态" clearable style="width: 150px">
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              style="width: 350px"
            />
          </el-form-item>
          <el-form-item label="关键词">
            <el-input
              v-model="listQuery.keyword"
              placeholder="订单号/客户名"
              style="width: 200px"
              class="filter-item"
              @keyup.enter="handleFilter"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">搜索</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <el-card>
      <div class="table-header">
        <div class="left">
          <span class="title">订单列表</span>
        </div>
        <div class="right">
<!--          <el-button type="success" size="small" @click="handleExport">导出Excel</el-button>-->
          <el-button type="primary" size="small" @click="fetchData">刷新</el-button>
        </div>
      </div>

      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="加载中..."
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column label="订单编号" prop="orderNo" align="center" width="180">
          <template #default="scope">
            <router-link :to="'/admin/order/detail/' + scope.row.id" class="link-type">
              {{ scope.row.orderNo }}
            </router-link>
          </template>
        </el-table-column>
        <el-table-column label="客户名称" prop="customerName" align="center" width="150" />
        <el-table-column label="商品名称" prop="productName" align="center" width="180" />
        <el-table-column label="金额" prop="amount" align="center" width="120">
          <template #default="scope">
            ¥{{ scope.row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="订单状态" prop="status" align="center" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" align="center" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleDetail(scope.row)">详情</el-button>
            <el-button type="warning" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="listQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </el-card>

    <!-- 添加流程记录对话框 -->
    <el-dialog title="添加流程记录" v-model="dialogProcessVisible" width="500px">
      <el-form :model="processForm" label-width="100px">
        <el-form-item label="流程类型">
          <el-select v-model="processForm.processType" placeholder="请选择流程类型" style="width: 100%">
            <el-option v-for="item in processTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="processForm.content" type="textarea" :rows="4" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogProcessVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProcessLog">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 更新状态对话框 -->
    <el-dialog title="更新订单状态" v-model="dialogStatusVisible" width="500px">
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="新状态">
          <el-select v-model="statusForm.status" placeholder="请选择订单状态" style="width: 100%">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="statusForm.remark" type="textarea" :rows="4" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogStatusVisible = false">取消</el-button>
          <el-button type="primary" @click="submitStatusUpdate">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑订单对话框 -->
    <el-dialog title="编辑订单" v-model="dialogEditVisible" width="500px">
      <el-form :model="editForm" label-width="100px" :rules="editRules" ref="editFormRef">
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择订单状态" style="width: 100%">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="editForm.remark" type="textarea" :rows="4" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogEditVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog title="删除确认" v-model="dialogDeleteVisible" width="400px">
      <div class="delete-confirm">
        <i class="el-icon-warning" style="color: #E6A23C; font-size: 24px;"></i>
        <p>确定要删除该订单吗？此操作不可恢复！</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogDeleteVisible = false">取消</el-button>
          <el-button type="danger" @click="submitDelete">确定删除</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderList, updateOrderStatus, addOrderProcessLog, deleteOrder } from '@/api/orderManagement'
import { formatDate } from '@/utils/index'

export default {
  name: 'OrderList',
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        size: 10,
        status: null,
        startDate: null,
        endDate: null,
        keyword: ''
      },
      dateRange: [],
      statusOptions: [
        { value: 0, label: '待付款' },
        { value: 1, label: '待确认' },
        { value: 2, label: '生产中' },
        { value: 3, label: '已发货' },
        { value: 4, label: '已完成' },
        { value: 5, label: '已取消' }
      ],
      processTypeOptions: [
        { value: 'payment', label: '付款' },
        { value: 'confirmation', label: '确认' },
        { value: 'production', label: '生产' },
        { value: 'shipping', label: '发货' },
        { value: 'completion', label: '完成' },
        { value: 'cancel', label: '取消' },
        { value: 'other', label: '其他' }
      ],
      currentOrder: null,
      dialogProcessVisible: false,
      dialogStatusVisible: false,
      processForm: {
        processType: '',
        content: ''
      },
      statusForm: {
        status: null,
        remark: ''
      },
      dialogEditVisible: false,
      dialogDeleteVisible: false,
      editForm: {
        id: null,
        status: null,
        remark: ''
      },
      editRules: {
        status: [
          { required: true, message: '请选择订单状态', trigger: 'change' }
        ],
        remark: [
          { required: true, message: '请输入备注信息', trigger: 'blur' }
        ]
      },
      loading: false
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      console.log('请求参数:', this.listQuery)
      const params = {
        ...this.listQuery,
        page: this.listQuery.page - 1
      }
      getOrderList(params).then(response => {
        console.log('订单列表响应:', response)
        if (response.data) {
          this.list = response.data.content || []
          this.total = response.data.totalElements || 0
          if (this.list.length === 0) {
            this.$message.info('暂无订单数据')
          }
        } else {
          this.$message.warning('返回数据格式不正确')
          this.list = []
          this.total = 0
        }
      }).catch(error => {
        console.error('获取订单列表失败:', error)
        this.$message.error('获取订单列表失败: ' + (error.message || '未知错误'))
        this.list = []
        this.total = 0
      }).finally(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      if (this.dateRange && this.dateRange.length === 2) {
        this.listQuery.startDate = this.dateRange[0]
        this.listQuery.endDate = this.dateRange[1]
      } else {
        this.listQuery.startDate = null
        this.listQuery.endDate = null
      }
      this.fetchData()
    },
    resetFilter() {
      this.listQuery = {
        page: 1,
        size: 10,
        status: null,
        startDate: null,
        endDate: null,
        keyword: ''
      }
      this.dateRange = []
      this.fetchData()
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },
    getStatusType(status) {
      const statusMap = {
        0: 'info',
        1: 'warning',
        2: 'warning',
        3: 'primary',
        4: 'success',
        5: 'danger'
      }
      return statusMap[status] || 'info'
    },
    getStatusText(status) {
      const statusMap = {
        0: '待付款',
        1: '待确认',
        2: '生产中',
        3: '已发货',
        4: '已完成',
        5: '已取消'
      }
      return statusMap[status] || '未知状态'
    },
    handleDetail(row) {
      this.$router.push(`/admin/order/detail/${row.id}`)
    },
    handleProcess(row) {
      this.$router.push(`/admin/order/process/${row.id}`)
    },
    handleStatusUpdate(row, newStatus) {
      this.currentOrder = row
      this.statusForm.status = newStatus || row.status
      this.dialogStatusVisible = true
    },
    handleAddLog(row) {
      this.currentOrder = row
      this.processForm = {
        processType: '',
        content: ''
      }
      this.dialogProcessVisible = true
    },
    submitStatusUpdate() {
      if (!this.statusForm.status) {
        this.$message.error('请选择状态')
        return
      }
      
      updateOrderStatus(this.currentOrder.id, this.statusForm.status, this.statusForm.remark)
        .then(() => {
          this.$message.success('状态更新成功')
          this.dialogStatusVisible = false
          this.fetchData()
        })
        .catch(err => {
          this.$message.error('状态更新失败: ' + err.message)
        })
    },
    submitProcessLog() {
      if (!this.processForm.processType) {
        this.$message.error('请选择流程类型')
        return
      }
      
      if (!this.processForm.content) {
        this.$message.error('请输入内容')
        return
      }
      
      const data = {
        processType: this.processForm.processType,
        content: this.processForm.content,
        operatorId: this.$store.getters.userId // 假设有用户ID存储在Vuex中
      }
      
      addOrderProcessLog(this.currentOrder.id, data)
        .then(() => {
          this.$message.success('流程记录添加成功')
          this.dialogProcessVisible = false
          this.fetchData()
        })
        .catch(err => {
          this.$message.error('流程记录添加失败: ' + err.message)
        })
    },
    handleExport() {
      this.$message.info('导出功能开发中...')
    },
    formatDate,
    handleEdit(row) {
      this.currentOrder = row
      this.editForm = {
        id: row.id,
        status: row.status,
        remark: row.remark || ''
      }
      this.dialogEditVisible = true
    },
    handleDelete(row) {
      this.currentOrder = row
      this.dialogDeleteVisible = true
    },
    submitEdit() {
      this.$refs.editFormRef.validate(valid => {
        if (valid) {
          // 显示加载状态
          this.loading = true
          
          // 调用更新订单状态的API
          updateOrderStatus(this.editForm.id, this.editForm.status, this.editForm.remark)
            .then(response => {
              if (response.data) {
                this.$message.success('订单更新成功')
                this.dialogEditVisible = false
                // 刷新列表
                this.fetchData()
              } else {
                this.$message.error('订单更新失败')
              }
            })
            .catch(err => {
              console.error('更新订单失败:', err)
              this.$message.error('订单更新失败: ' + (err.message || '未知错误'))
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    submitDelete() {
      if (!this.currentOrder) return
      
      deleteOrder(this.currentOrder.id)
        .then(() => {
          this.$message.success('订单删除成功')
          this.dialogDeleteVisible = false
          this.fetchData()
        })
        .catch(err => {
          this.$message.error('订单删除失败: ' + (err.message || '未知错误'))
        })
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
.filter-card {
  margin-bottom: 20px;
}
.form-inline {
  display: flex;
  flex-wrap: wrap;
}
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.title {
  font-size: 18px;
  font-weight: bold;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.link-type {
  color: #409EFF;
  text-decoration: none;
}
.link-type:hover {
  text-decoration: underline;
}
.delete-confirm {
  text-align: center;
  padding: 20px 0;
}
.delete-confirm p {
  margin-top: 10px;
  color: #606266;
}
</style> 